package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.Food;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        //批量导入预约设置信息
        orderSettings.forEach(orderSetting -> {
            // 检查此预约设置日期是否存在预约设置
            int count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
            //如果已经存储预约设置, 更新预约信息
            if (count > 0) {
                orderSettingDao.updateNumberByOrderDate(orderSetting);
                return;
            }
            //如果不存储预约设置, 保存预约信息
            orderSettingDao.add(orderSetting);

        });
    }

    @Override
    public List<Map<String, Object>> getOrderSettingsByMonth(String date) throws ParseException {
        Date time = new SimpleDateFormat("yyyy-MM").parse(date);
        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingsByMonth(time);

        List<Map<String, Object>> list = orderSettings.stream().map(orderSetting -> {
            HashMap<String, Object> map = new HashMap<>();

            Calendar calendar = Calendar.getInstance(); // 默认是当前时间的日历  2020-08-09
            calendar.setTime(orderSetting.getOrderDate());  // 2020-09-01

            map.put("date", calendar.get(Calendar.DAY_OF_MONTH));
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());

            return map;
        }).collect(Collectors.toList());

        return list;
    }

    @Override
    public void updateOrderSettingNumber(OrderSetting orderSetting) {
        //查询数据库中是否有预约数据
        int count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        //如果数据库中有预约数据 , 更新预约数据
        if (count > 0) {
            orderSettingDao.updateNumberByOrderDate(orderSetting);
            return;
        }

        //如果数据库中没有预约数据 , 添加预约数据
        orderSettingDao.add(orderSetting);
    }


}
